//
//  BBMouseFakerController.m
//  BBTouch
//
//  Created by ben smith on 8/22/08.
//  This file is part of BBTouch.
//
//  BBTouch is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  BBTouch is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.

//  You should have received a copy of the GNU Lesser General Public License
//  along with BBTouch.  If not, see <http://www.gnu.org/licenses/>.
// 
//  Copyright 2008 Ben Britten Smith ben@benbritten.com .
//
#import "BBMouseFakerController.h"
#import "BBScreenSelectionView.h"
#import "BBBlobEvent.h"


@implementation BBMouseFakerController

-(void)awakeFromNib
{
	isActive = NO;
}

-(void)blobDown:(NSNotification*)note
{
	if (!isActive) return;
	[super blobDown:note];
	if ([blobPoints count] == 1) {
		// then we want to simulate a mouse down as well
		// need to get the cursor position in global screen coords
		fakeMouseID = [(BBBlobEvent*)[note object] blobID];
		NSPoint p = [self fakeMousePointInSelectedScreen];
		CGError err = CGPostMouseEvent (NSPointToCGPoint(p), 1, 1, 1);
	}
}

-(void)blobDone:(NSNotification*)note
{
	if (!isActive) return;
	// check for two types of events here:
	// if the blob is still in the list, then it is a mouse drag
	// if it isnt in the list then it is a mouse up
	if (fakeMouseID < 0) return;
	
	NSInteger index = [self indexOfBlobWithID:fakeMouseID];
	if (index == NSNotFound) {
		// then the blob left, mouse up
		NSPoint p = [self fakeMousePointInSelectedScreen];
		CGError err = CGPostMouseEvent (NSPointToCGPoint(p), 1, 1, 0);		
		fakeMouseID = -1;
		return;
	}
	
	NSPoint p = [self fakeMousePointInSelectedScreen];
	CGError err = CGPostMouseEvent (NSPointToCGPoint(p), 1, 1, 1);		
}


-(NSPoint)fakeMousePointInSelectedScreen
{
	NSLog(@"fakemouseid: %d",fakeMouseID);
	
	NSInteger index = [self indexOfBlobWithID:fakeMouseID];

	if (index == NSNotFound) return NSZeroPoint;
	
	NSRect screenFrame = [screenSelector.chosenScreen frame];

	BBBlobEvent * fakeMouse = [blobPoints objectAtIndex:index];
	// now scale the point into our rectangle
	
	NSPoint mouse = [fakeMouse screenLocation];
	mouse.x *= NSWidth(screenFrame);
	mouse.y = 1.0 - mouse.y; // flip, screen coords are flipped
	mouse.y *= NSHeight(screenFrame);

	mouse.x += NSMinX(screenFrame);
	mouse.y += NSMinY(screenFrame);
//	NSLog(@"mouse: %@ %@",NSStringFromPoint(mouse),NSStringFromRect(screenFrame));
	return mouse;
}

@end
